//
//  ALTagView.m
//  ios-loan-assistant
//
//  Created by anlun on 2018/6/3.
//  Copyright © 2018年 guoqingping. All rights reserved.
//

#import "ALTagView.h"
//@interface ALTagView ()
//@property (strong, nonatomic, nullable) NSMutableArray *tags;
//@property (assign, nonatomic) BOOL didSetup;
//
//@end
@implementation ALTagView
- (void)layoutTags {
//    if (self.didSetup || !self.tags.count) {
//        return;
//    }
    NSInteger curRowNum=0; //默认0行
    NSInteger totalCount=0; //总共个数
    NSArray *subviews = self.subviews;
    UIView *previousView = nil;
    CGFloat topPadding = self.padding.top;
    CGFloat leftPadding = self.padding.left;
    CGFloat rightPadding = self.padding.right;
    CGFloat itemSpacing = self.interitemSpacing;
    CGFloat lineSpacing = self.lineSpacing;
    CGFloat currentX = leftPadding;
    self.preferredMaxLayoutWidth=[UIScreen mainScreen].bounds.size.width;
    if (!self.singleLine && self.preferredMaxLayoutWidth > 0) {
        for (UIView *view in subviews) {
            CGSize size = view.intrinsicContentSize;
            if (previousView) {
                CGFloat width = size.width;
                currentX += itemSpacing;
                if (currentX + width + rightPadding <= self.preferredMaxLayoutWidth) {
                    view.frame = CGRectMake(currentX, CGRectGetMinY(previousView.frame), size.width, size.height);
                    currentX += size.width;
                } else {
                    curRowNum+=1; //加一行
                    
                    CGFloat width = MIN(size.width, self.preferredMaxLayoutWidth - leftPadding - rightPadding);
                    view.frame = CGRectMake(leftPadding, CGRectGetMaxY(previousView.frame) + lineSpacing, width, size.height);
                    currentX = leftPadding + width;
                }
            } else {
                CGFloat width = MIN(size.width, self.preferredMaxLayoutWidth - leftPadding - rightPadding);
                view.frame = CGRectMake(leftPadding, topPadding, width, size.height);
                currentX += width;
            }
            
            previousView = view;
            
            if (curRowNum<2) { //一行 和 二行 的时候统计总个数
                totalCount+=1;
            }
        }
       
        //遍历完了，返回总个数
        if (self.didTotalCount&&totalCount>0) {
            self.didTotalCount(totalCount);
        }
        
    } else {
        for (UIView *view in subviews) {
            CGSize size = view.intrinsicContentSize;
            view.frame = CGRectMake(currentX, topPadding, size.width, size.height);
            currentX += size.width;
            currentX += itemSpacing;
            
            previousView = view;
        }
    }
    
//    self.didSetup = YES;
}

@end
